import pandas as pd
import json
from http_requests import HttpRequest
import time
import requests
from ocr import imgOcr, userNameOcr
from private_message_send import privateMessage
import random

max_calls = 50

def loop(all_users, http_client, keywords, loopCount, ocr_engine, loop_index,private_message_List,checkbox_value,log_callback):
    global max_calls
    # 存储所有的 user 数据
    time.sleep(3)

    # 检查是否处理完所有关键词
    if loop_index >= len(keywords):
        save_to_excel(all_users, keywords)
        return

    # 打开视频号搜索
    data = {"x": 890.0, "y": 175.0}
    response = http_client.post("click", data=json.dumps(data), headers={"Content-Type": "application/json"})
    if response.get("code") == 1:
        print("打开视频号搜索成功")
        log_callback("打开视频号搜索成功")

    keyword = keywords[loop_index]
    time.sleep(4)

    # 输入关键词
    data = {"value": keyword}
    response = http_client.post("inputText", data=json.dumps(data), headers={"Content-Type": "application/json"})
    if response.get("code") == 1:
        print("设置微信视频号搜索内容")
        log_callback("设置微信视频号搜索内容")

    time.sleep(4)
    # 点击搜索
    data = {"x": 900.0, "y": 165.0}
    response = http_client.post("click", data=json.dumps(data), headers={"Content-Type": "application/json"})
    if response.get("code") == 1:
        print("点击搜索")
        log_callback("点击搜索")

    time.sleep(7)
    # 筛选
    data = {"x": 980.0, "y": 300.0}
    response = http_client.post("click", data=json.dumps(data), headers={"Content-Type": "application/json"})
    if response.get("code") == 1:
        print("筛选")
        log_callback("筛选")

    time.sleep(2)
    # 点击最新
    data = {"x": 605.0, "y": 425.0}
    response = http_client.post("click", data=json.dumps(data), headers={"Content-Type": "application/json"})
    if response.get("code") == 1:
        print("点击最新")
        log_callback("点击最新")

    time.sleep(4)

    # 筛选
    data = {"x": 980.0, "y": 300.0}
    response = http_client.post("click", data=json.dumps(data), headers={"Content-Type": "application/json"})
    if response.get("code") == 1:
        print("关闭筛选")
        log_callback("关闭筛选")

    time.sleep(2)
    # 点击item
    data = {"x": 300.0, "y": 755.0}
    response = http_client.post("click", data=json.dumps(data), headers={"Content-Type": "application/json"})
    if response.get("code") == 1:
        print("点击item")
        log_callback("点击item")

    for i in range(loopCount):
        print(f"处理第 {i + 1} 个用户，关键词: {keyword}")
        log_callback(f"处理第 {i + 1} 个用户，关键词: {keyword}")
        time.sleep(4)
        if (i + 1) % 5 == 0:
            try:
                # 检查是否到达最后一个
                response = http_client.get("screenShotBase64")
                is_last = userNameOcr(response['data'], ocr_engine)
                if is_last:
                    print("已到最后一个")
                    log_callback("已到最后一个")
                    time.sleep(2)
                    # 返回
                    data = {"x": 55.0, "y": 160.0}
                    response = http_client.post("click", data=json.dumps(data),
                                                headers={"Content-Type": "application/json"})
                    if response.get("code") == 1:
                        print("返回")
                        log_callback("返回")
                    break
            except Exception as e:
                print(f"检查最后一个用户时出错: {str(e)}")
                log_callback(f"检查最后一个用户时出错: {str(e)}")

        time.sleep(4)
        # 点击用户详情
        data = {"x": 210.0, "y": 2135.0}
        response = http_client.post("click", data=json.dumps(data), headers={"Content-Type": "application/json"})
        if response.get("code") == 1:
            print("点击用户详情")
            log_callback("点击用户详情")

        time.sleep(5)
        # 截图并识别用户信息
        response = http_client.get("screenShotBase64")

        try:
            # 随机单日次数进入50次
            if checkbox_value:
                call_count = 0  # 初始化调用次数
                target = False

                if call_count < max_calls:
                    # 每次随机决定是否调用
                    if random.random() < 0.5:  # 50% 概率调用
                        print(f"Calling privateMessage, attempt {call_count + 1}")
                        target = True

                    else:
                        target = False
                        print(f"Skipping attempt {call_count + 1}")

                if target == False:
                    print(f"保存截图")
                    log_callback("保存信息")
                    imgOcr(response['data'],keyword)
                else:
                    print(f"发送私信")
                    log_callback("发送私信")
                    result = privateMessage(http_client,response['data'],private_message_List)
                    if result == True:
                        call_count += 1
            else:
                print(f"保存截图")
                log_callback("保存信息")
                imgOcr(response['data'], keyword)

        except Exception as e:
            print(e)
        finally:
            del response  # 强制释放
            if 'data' in locals(): del locals()['data']  # 确保删除大内存字段

        time.sleep(3)
        # 关闭用户详情
        data = {"x": 560.0, "y": 380.0}
        response = http_client.post("click", data=json.dumps(data), headers={"Content-Type": "application/json"})
        if response.get("code") == 1:
            print("关闭用户详情")
            log_callback("关闭用户详情")

        time.sleep(3)
        # 滑动到下一个
        data = {"x1": 0.2, "y1": 800, "x2": 0.2, "y2": 100, "duration": 500}
        response = http_client.post("swipe", data=json.dumps(data), headers={"Content-Type": "application/json"})
        if response.get("code") == 1:
            print("滑动下一个")
            log_callback("滑动下一个")

    # 处理下一个关键词
    time.sleep(2)
    data = {"x": 55.0, "y": 160.0}
    response = http_client.post("click", data=json.dumps(data), headers={"Content-Type": "application/json"})
    if response.get("code") == 1:
        print("返回")
        log_callback("返回")

    # 递归调用处理下一个关键词
    loop(all_users, http_client, keywords, loopCount, ocr_engine, loop_index + 1,private_message_List,checkbox_value,log_callback)


def save_to_excel(all_users, keywords):
    if not all_users:
        print("没有找到用户数据")
        return

    try:
        df = pd.DataFrame(all_users)
        filename = f"微信视频号_{'_'.join(keywords)}.xlsx"
        df.to_excel(filename, index=False)
        print(f"所有用户数据已保存到 {filename}")
    except Exception as e:
        print(f"保存Excel文件时出错: {str(e)}")


def init(keyword, ip, loopCount, ocr_engine,private_message_List,checkbox_value,log_callback):
    all_users = []
    http_client = HttpRequest(base_url="http://" + ip + ":18080/api")

    print(keyword, loopCount, ip)
    log_callback(f"{keyword} {ip}")
    try:
        # 关闭微信
        response = http_client.get("stopPackage", params={"packageName": "com.tencent.mm"})
        print(response)

        if response is None:
            print(f"设备{ip}连接失败！")
            log_callback(f"设备{ip}连接失败！")
            #wx.CallAfter(self.show_error_message, f"设备{ip}连接失败！")
            return

        if response.get("code") == 1:
            log_callback(f"设备{ip}连接成功")
            time.sleep(5)
            # 打开微信
            response = http_client.get("startPackage", params={"packageName": "com.tencent.mm"})
            print(response)
            if response.get("code") == 1:
                time.sleep(6)
                print("打开微信成功")
                log_callback(f"打开微信成功")
                # 打开发现
                data = {"x": 680.0, "y": 2190.0}
                response = http_client.post("click", data=json.dumps(data),
                                            headers={"Content-Type": "application/json"})
                if response.get("code") == 1:
                    print("打开微信发现成功")
                    log_callback(f"打开微信发现成功")
                time.sleep(5)
                # 打开视频号
                data = {"x": 1.0, "y": 485.0}
                response = http_client.post("click", data=json.dumps(data),
                                            headers={"Content-Type": "application/json"})
                if response.get("code") == 1:
                    print("打开微信视频号成功")
                    log_callback(f"打开微信视频号成功")

                # data = {"x": 5040.0, "y": 300.0}
                # response = http_client.post("click", data=json.dumps(data),
                #                             headers={"Content-Type": "application/json"})
                # if response.get("code") == 1:
                #     print("暂停")
                #     log_callback(f"暂停视频播放")
                # 开始循环处理
                loop(all_users, http_client, keyword, loopCount, ocr_engine, 0,private_message_List,checkbox_value,log_callback)

        else:
            print(f"设备{ip}连接失败！")
            log_callback(f"设备{ip}连接失败！")
            pass
            #wx.MessageBox(f"设备{ip}连接失败！")

    except requests.exceptions.Timeout:
        print(f"设备{ip}连接超时！")
        log_callback(f"设备{ip}连接超时！")
        pass
        #wx.CallAfter(self.show_error_message, f"设备{ip}连接超时！")
    except requests.exceptions.ConnectionError as e:
        print(f"无法连接到设备 {ip}，错误信息: {str(e)}")
        log_callback(f"无法连接到设备 {ip}，错误信息: {str(e)}")
        pass
        #wx.CallAfter(self.show_error_message, f"无法连接到设备 {ip}，错误信息: {str(e)}")
    except requests.exceptions.RequestException as e:
        print(f"请求异常: {str(e)}")
        log_callback(f"请求异常: {str(e)}")
        pass
        #wx.CallAfter(self.show_error_message, f"请求异常: {str(e)}")
    finally:
        del http_client  # 确保关闭